/*
    echo_client.c
        Achieve the echo client
    BeginnerC
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define DEFAULT_BUFFER_SIZE 4096
int main(int argc, char *argv[])
{
    int client_fd = 0;
    char buffer[DEFAULT_BUFFER_SIZE] = {};
    struct sockaddr_in address = {};
    if (argc != 3)
    { 
        puts("Usage: EchoClient <ip address> <port>");
        return 0;
    }
    client_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (client_fd < 0)
    {
        puts("Error: socket failed");
        return -1;
    }
    address.sin_family = AF_INET;
    address.sin_port = htons(atoi(argv[2]));
    if (inet_pton(AF_INET, argv[1], &address.sin_addr) <= 0)
    {
        puts("Error: Address translate failed");
        return -1;
    }
    if (connect(client_fd, (const struct sockaddr *)&address, sizeof(address)) < 0)
    {
        puts("Error: Client failed");
        return -1;
    }
    while (1)
    {
        int ret = 0;
        puts("Please give the content you want to send:");
        {
            int position = 0;
            char c = '\n';
            while ('\n' != (c = getchar()) && position < sizeof(buffer))
            {
                buffer[position] = c;
            }
            buffer[position + 1] = '\0';
        }
        ret = write(client_fd, buffer, sizeof(buffer));
        if (ret < 0)
        {
            break;
        }
        memset(buffer, 0, sizeof(buffer));
        ret = read(client_fd, buffer, sizeof(buffer));
        if (ret <= 0)
        {
            break;
        }
        printf("Received: %s\n", buffer);
    }
    printf("The Echo client is end.\n");
    return 0;
}